<template>
  <a-modal title="节假日" width="calc(100vw - 40px)" v-model:visible="visible">
    <div class="holiday-config-wrapper">
      <a-alert>
        <template #icon> <icon-exclamation-circle /> </template>价格展示优先级：自定义价格 > 法定节假日价格 > 周末价 > 基础价</a-alert
      >
      <div class="form-block">
        <div class="car-model-info">
          <div class="car-model-name">{{ holidayConfigInfo.modelName }}</div>
          <div class="car-model-field-info flex">
            <field-item style="margin-right: 56px" label="车辆数量">{{ holidayConfigInfo.carNumber }}</field-item>
            <field-item class="flex-1" label="应用门店">{{ holidayConfigInfo.siteNameList?.join(' | ') }}</field-item>
          </div>
        </div>
      </div>
      <page-form :model="form" ref="formRef" layout="vertical" style="overflow: hidden">
        <card>
          <template #title>
            <holiday-config-switch-title v-model="form.holidaySwitch" title="节假日价" titleTooltipContent="法定节假日的车型价格">
              <a-button size="mini" class="config-holiday-btn" type="outline" @click="holidayDateConfigClick">配置节假日时间</a-button>
            </holiday-config-switch-title>
          </template>
          <page-form-row v-if="form.holidaySwitch" :gutter="{ xs: 10, sm: 40, md: 40, xl: 80 }">
            <page-form-item v-for="(item, index) in holidayList" :key="index" size="1/4">
              <input-card :title="item.title">
                <priceForm :record="form" :priceType="item.prop" />
              </input-card>
            </page-form-item>
          </page-form-row>
        </card>
        <card :showDivider="false">
          <template #title>
            <holiday-config-switch-title
              v-model="form.customSwitch"
              title="自定义价"
              titleTooltipContent="商户配置自定义时间段价格"
              @change="changeCustomPriceSwitchFn"
            />
          </template>
          <page-form-row v-if="form.customSwitch" :gutter="{ xs: 10, sm: 40, md: 40, xl: 80 }">
            <template v-if="form.custPriceList && form.custPriceList.length > 0">
              <page-form-item v-for="(item, index) in form.custPriceList" :key="index" size="1/4">
                <input-card :closeable="index >= 0" @delete="deleteCustomDateFn(index)">
                  <template #title>
                    <page-form-item
                      size="1"
                      style="margin-bottom: 0"
                      required
                      label="自定义日期"
                      :field="`custPriceList.${index}.dateRange`"
                      :rules="{ required: true, message: '请选择自定义日期' }"
                    >
                      <i-range-picker
                        v-model="item.dateRange"
                        :disabledDate="disabledCustomDate"
                        @change="(val) => changeCustomDateFn(val, item)"
                        class="w-full"
                      />
                    </page-form-item>
                  </template>
                  <page-form-item size="1" class="my-0">
                    <div class="custom-price-wrapper">
                      <div class="custom-price-title">日租价</div>
                      <div class="custom-price-content">
                        <priceForm :record="item" :fieldPrefix="`custPriceList.${index}`" priceType="price" />
                      </div>
                    </div>
                  </page-form-item>
                </input-card>
              </page-form-item>
            </template>
            <!-- 添加节点 -->
            <page-form-item size="1/4">
              <div class="add-custom-date w-full" @click="addCustomDateFn" :style="{ height: customAddBtnHeight }">
                <div class="add-custom-btn-wrapper flex">
                  <div class="add-custom-btn-content">
                    <icon-plus style="font-size: 18px" />
                    <div class="new-custom-date">新增自定义日期</div>
                  </div>
                </div>
              </div>
            </page-form-item>
          </page-form-row>
        </card>
      </page-form>
    </div>
    <template #footer>
      <a-button @click="visible = false">关闭</a-button>
      <a-button type="primary" :loading="okLoading" @click="submitFn">确认</a-button>
    </template>
  </a-modal>
  <!-- 节假日日期配置 -->
  <holidayDateConfigModal ref="holidayDateConfigModalRef" />
</template>

<script setup name="HolidayConfig">
  import { ref, computed, provide } from 'vue'
  import { getTemplateHolidayConfig, saveTemplateHolidayConfig } from '@/api/business/price.js'
  import holidayConfigSwitchTitle from './holiday-config-switch-title.vue'
  import inputCard from './holiday-config-input-card.vue'
  import priceForm from '../sorder-config/price-form.vue'
  import holidayDateConfigModal from './holiday-date-config-modal.vue'
  import dayjs from 'dayjs'
  const emit = defineEmits(['cancel', 'ok'])
  import { Notification } from '@arco-design/web-vue'
  const formRef = ref(null)
  provide('formRef', formRef)
  // 判断自定义价格是否有重叠
  const isCustomDateOverlap = () => {
    let priceList = form.value.custPriceList
    let isOverLap = false
    priceList.forEach((item, index) => {
      let startTime = item.startTime
      let endTime = item.endTime
      let startTimeStamp = dayjs(startTime).valueOf()
      let endTimeStamp = dayjs(endTime).valueOf()
      for (var i = 0; i < priceList.length; i++) {
        if (i == index) {
          continue
        } else {
          let _item = priceList[i]
          let _startTime = _item.startTime
          let _endTime = _item.endTime
          // 判断是否有重叠
          // 由于自定义日期必填，如果没填不会走到这里，所以此处认为日期都不为空
          // 1 比较开始时间
          let _startTimeStamp = dayjs(_startTime).valueOf()
          let _endTimeStamp = dayjs(_endTime).valueOf()
          // _startTime 在 startTime 和 endTime 之间
          if (_startTimeStamp >= startTimeStamp && _startTimeStamp <= endTimeStamp) {
            setFeildWarn(index)
            isOverLap = true
            break
          }
          // _endTime 在 startTime 和 endTime 之间
          if (_endTimeStamp >= startTimeStamp && _endTimeStamp <= endTimeStamp) {
            setFeildWarn(index)
            isOverLap = true
            break
          }
        }
      }
    })

    return isOverLap
  }
  // 自定义新增按钮高度
  const customAddBtnHeight = computed(() => {
    const channelPriceList = form.value.channelPriceList || []
    if (channelPriceList.length > 0) {
      if (channelPriceList.length == 1) {
        return '289px'
      } else {
        return `${289 + (channelPriceList.length - 1) * 70}px`
      }
    }
    // 默认只有
    return '217px'
  })
  // 自定义价格单条数据
  const customPriceItem = computed(() => {
    return {
      startTime: '',
      endTime: '',
      price: '',
      channelPriceList: [
        ...form.value.channelPriceList.map((item) => {
          return {
            sourceId: item.sourceId,
            sourceIdName: item.sourceIdName,
            price: '',
          }
        }),
      ],
    }
  })
  // 配置节假日时间
  const holidayDateConfigModalRef = ref(null)
  const holidayDateConfigClick = () => {
    holidayDateConfigModalRef.value.open()
  }
  const setFeildWarn = (index) => {
    formRef.value.setFields({
      [`custPriceList.${index}.dateRange`]: {
        status: 'error',
        message: '当前自定义日期，与其他日期有重叠，请重新设置',
      },
    })
  }
  const okLoading = ref(false)
  // 保存
  const submitFn = () => {
    formRef.value.validate((error) => {
      if (!error) {
        const param = {
          ...form.value,
        }
        let isoverLap = false
        // 自定义日期开关打开状态下，需要验证日期是否有重叠
        if (form.value.customSwitch) {
          isoverLap = isCustomDateOverlap()
        } else {
          // 处理空对象情况
          let custPriceList = param.custPriceList
          for (let i = 0; i < custPriceList.length; i++) {
            let item = custPriceList[i]
            // 没有选定开始日期和结束日期，则删除当前项
            if (!item.startTime && !item.endTime) {
              custPriceList.splice(i, 1)
              i--
            }
          }
        }
        if (!isoverLap) {
          okLoading.value = true
          saveTemplateHolidayConfig(param)
            .then(() => {
              // 保存接口
              Notification.success({
                content: '保存成功',
                closable: true,
                duration: 3000,
              })
              visible.value = false
              emit('ok')
            })
            .finally(() => {
              okLoading.value = false
            })
        }
      }
    })
  }
  // 自定义价格开关开启
  const changeCustomPriceSwitchFn = (val) => {
    // 需要检测是否有默认值
    if (val) {
      if (form.value.custPriceList.length == 0) {
        const cloneVal = JSON.parse(JSON.stringify(customPriceItem.value))
        form.value.custPriceList.push(cloneVal)
      }
    }
  }
  // 日期禁用逻辑，不能选择今天之前的时间
  const disabledCustomDate = (current) => {
    return dayjs(current).isBefore(dayjs().subtract(1, 'day')) || dayjs(current).isAfter(dayjs().add(120, 'day'))
  }
  const holidayList = [
    { title: '元旦', prop: 'newYearPrice' },
    { title: '春节', prop: 'springPrice' },
    { title: '清明节', prop: 'sweepingDay' },
    { title: '劳动节', prop: 'labourPrice' },
    { title: '端午节', prop: 'dragonBoatPrice' },
    { title: '中秋节', prop: 'midAutumnPrice' },
    { title: '国庆节', prop: 'nationalPrice' },
  ]
  const changeCustomDateFn = (val = [], item) => {
    item.startTime = val[0]
    item.endTime = val[1]
  }
  // 添加自定义价格
  const addCustomDateFn = () => {
    const cloneVal = JSON.parse(JSON.stringify(customPriceItem.value))
    form.value.custPriceList.push(cloneVal)
  }
  // 删除自定义价格
  const deleteCustomDateFn = (index) => {
    form.value.custPriceList.splice(index, 1)
  }
  const form = ref({
    // 周末开关
    weekendSwitch: 0,
    // 周末类别
    weekendSort: 1,
    // 节假日开关
    holidaySwitch: 0,
    // 自定义开关 默认关闭
    customSwitch: 0,
    // 自定义价格数组
    custPriceList: [],
    // 渠道价格信息
    channelPriceList: [],
  })

  // 节假日时间配置信息
  const holidayConfigInfo = ref({})

  // 重置 form
  const resetForm = () => {
    formRef.value.clearValidate()
  }
  const visible = ref(false)
  const open = (record) => {
    console.log(record)
    visible.value = true
    resetForm()
    let id = record.id
    if (id) {
      // 读取配置
      getTemplateHolidayConfig({ id }).then((res) => {
        const result = res.result
        holidayConfigInfo.value = result
        // 处理自定义 开始
        let custPriceList = result.custPriceList
        if (custPriceList?.length > 0) {
          custPriceList.forEach((item) => {
            if (item.startTime && item.endTime) {
              item.dateRange = [item.startTime, item.endTime]
            }
          })
        }
        // 处理自定义 结束
        form.value = result
        // 更新 priceModelId
        form.value.priceModelId = id
        // 处理默认值，不处理默认值传递接口为 null，可能会出问题
        result.weekendSwitch == null ? (form.value.weekendSwitch = 0) : ''
        result.weekendSort == null ? (form.value.weekendSort = 1) : ''
        result.holidaySwitch == null ? (form.value.holidaySwitch = 0) : ''
        result.customSwitch == null ? (form.value.customSwitch = 0) : ''
        result.custPriceList == null ? (form.value.custPriceList = []) : ''
      })
    }
  }
  defineExpose({
    open,
  })
</script>

<style lang="less" scoped>
  .form-block {
    background: rgba(247, 248, 250, 0.5);
    padding: 20px;
    margin: 20px 0;
  }
  .car-model-name {
    color: var(--color-text-1);
    font-weight: 600;
    font-size: 20px;
    margin-bottom: 14px;
  }
  .add-custom-date {
    cursor: pointer;
    border-radius: 2px 2px 2px 2px;
    border: 1px solid #e5e8ef;
    display: flex;
    align-items: center;
    .add-custom-btn-wrapper {
      width: 100%;
      justify-content: center;
      align-items: center;
      .add-custom-btn-content {
        text-align: center;
        .new-custom-date {
          font-size: 12px;
          color: #86909c;
          margin-top: 17px;
        }
      }
    }
  }
  .holiday-config-wrapper {
    max-height: calc(100vh - 210px);
  }
  .holiday-config-wrapper {
    :deep(.custom-form-item .custom-input-number) {
      width: 100%;
    }
  }
  .custom-price-wrapper {
    width: 100%;
    .custom-price-title {
      height: 24px;
      font-weight: 600;
      font-size: 16px;
      color: #1d2129;
      line-height: 24px;
      margin-bottom: 10px;
    }
  }
  .config-holiday-btn {
    height: 18px;
    padding: 0 8px;
    margin-left: 12px;
    color: #1890ff !important;
    border-color: #1890ff !important;
  }
</style>
